import json
from pathlib import Path
from pickle import FALSE
from urllib.request import Request
from src.students import Student
from src.manager import CourseManager
from src.manager import StudentManager
from src.login import login, logout, is_login


class Main:
    root_path = Path(__file__).parent
    __student_data_db = root_path.joinpath('data', StudentManager.students_db)
    __courses_data_db = root_path.joinpath('data', CourseManager.coursers_db)

    def __init__(self):
        self.student_manager = StudentManager(self.__student_data_db)
        self.courses_manager = CourseManager(self.__courses_data_db)

    @is_login
    def create_students(self):
        """添加学生"""
        name = input('请输入姓名>>>:').strip()
        age = int(input('请输入年龄>>>:'))
        self.student_manager.add_student(name, age)
        print(f'添加学生 {name} 成功')

    @is_login
    def query_students(self):
        """查询所有学生"""
        student_id = input('请输出学生id >>>').strip()
        result = self.student_manager.get_student(student_id)
        # 这里返回的设计不太合理，前端和后端交互的过程中不应该返回对象，因该返回序列后的数据
        # 错误保留下来作为提醒
        if not isinstance(result, Student):
            if result.get('code') == 603:
                print('查询学生信息失败')
                return
        print(f'查询学生信息:::\n {json.dumps(result.to_dict, indent=4, ensure_ascii=False)}')

    def query_student_course(self):
        """查询学生课程"""
        student_id = input('请输出学生id >>>').strip()
        self.student_manager.query_curses(student_id, self.courses_manager.courses)

    def query_course(self):
        """查询课程"""
        course_id = input('请输入课程ID>>>:').strip()
        name = input('请输入课程名称>>>:').strip()
        self.courses_manager.query_course(course_id, name)

    def query_all_courses(self):
        """查询所有课程"""
        self.courses_manager.show_courses()

    @is_login
    def add_course(self):
        """添加课程，不是给学生选课"""
        course_name = input('请输入课程名称>>>:').strip()
        credit = int(input('请输入学分>>>:'))
        result = self.courses_manager.add_course(course_name, credit)
        if result['code'] == 800:
            print(result['message'])
        elif result['code'] == 803:
            print(result['message'])
        else:
            print(f'')

    @is_login
    def del_course(self):
        course_code = input('请输入课程代码>>>:').strip()
        result = self.courses_manager.drop_course(course_code)
        if result['code'] == 800:
            print(result['message'])
        elif result['code'] == 804:
            print(result['message'])

    @classmethod
    def exit(cls):
        logout()
        print("感谢您的使用，再见！")
        exit(0)

    def run(self):
        print(f"{'=' * 16}*欢迎进入YANT Python学院*{'=' * 16}")
        while True:
            # print(f"1: 登录；2:查看所有课程；3:查看指定课程；4:添加课程；5:删除课程；10:退出系统")
            try:
                # choice = int(input("请选择 >>> "))
                # 这个版本维护太麻烦，修改为用字典维护
                # match choice:
                #     case 1:
                #         login()
                #     case 2:
                #         self.query_all_courses()
                #
                #     case 3:
                #         self.query_course()
                #
                #     case 4:
                #         self.add_course()
                #     case 5:
                #         self.del_course()
                #
                #     case 6:
                #         self.create_students()
                #     case 10:
                #         logout()
                #         print("感谢您的使用，再见！")
                #         exit(0)
                #     case _:
                #         print("⚠️ 无效指令")

                ui_dict = {
                    '1': {
                        'func': login,
                        'desc': '登录'
                    },
                    '2': {

                        'func': self.query_all_courses,
                        'desc': '查看所有课程'
                    },
                    '3': {
                        'func': self.query_course,
                        'desc': '查看指定课程'
                    },
                    '4': {
                        'func': self.add_course,
                        'desc': '添加课程'
                    },
                    '5': {
                        'func': self.del_course,
                        'desc': '删除课程'
                    },
                    '6': {
                        'func': self.create_students,
                        'desc': '添加学生'

                    },

                    '7': {
                        'func': self.query_students,
                        'desc': '查看学生'

                    },
                    '8': {
                        'func': self.query_student_course,
                        'desc': '查看学生课程信息'

                    },

                    '10': {
                        'func': self.exit,
                        'desc': '退出系统'
                    },
                }
                func_str_list = '|'
                for key, value in ui_dict.items():
                    func_str_list += f"{key} {value['desc']}; |"
                print(func_str_list)
                print("=^<<<====*====>>>^=" * 3)
                choice = input("请选择 >>> ").strip()
                func = ui_dict.get(choice, None)
                if func:
                    func['func']()
                else:
                    print("⚠️ 无效指令")



            except KeyboardInterrupt:
                print('退出程序')
                exit(1)

            except Exception as err:
                print(f"程序出现未知异常：{err}")
            print('')
            print("=^<<<====*====>>>^=" * 3)


if __name__ == '__main__':
    st1 = {
        'name': 'Yant',
        'age': 28,
        'id': 'YA20250228456852'
    }

    Main().run()
